package com.ldn.basic.utils;

import cn.hutool.core.date.DateUnit;
import cn.hutool.cron.task.Task;
import jakarta.validation.constraints.NotBlank;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;

/**
 * @author 李大牛家的牛 (scafel@163.com)
 * @createDate 2024/9/6 - 9:28
 * @description ...
 **/
@Slf4j
@Component
public class CronUtil {

    private static final Map<String, String> cronMap = new ConcurrentHashMap<>();

    public static void setCronTask(String msg, String cronId,long time, Function<Void, Void> after) {
        if (cronMap.containsKey(cronId)){
            return;
        }
        if (DateUtils.getNumberForNow(time, DateUnit.SECOND) <= 0){
            after.apply(null);
            return ;
        }
        cronMap.put(cronId, cronId);
        cn.hutool.cron.CronUtil.schedule(cronId, DateUtils.onlyOnceCron(time), new Task() {
            @Override
            @Transactional
            public void execute() {
                log.info("定时任务，开始执行" + DateUtils.formatDate(time) + "-" + msg);
                try {
                    after.apply(null);
                    cn.hutool.cron.CronUtil.remove(cronId);
                    cronMap.remove(cronId);
                }catch (Exception e){
                    log.error("抽奖失败", e);
                }
            }
        });
    }


    public static void removeCronTask(@NotBlank String cronId) {
        cn.hutool.cron.CronUtil.remove(cronId);
        cronMap.remove(cronId);
    }

}
